/**
 * 分镜项目服务
 *
 * 提供分镜项目的CRUD操作和内容管理
 */

import { db } from './indexedDB/database'
import { ContentType, type Content, type StoryboardData } from '../../types/document'
import {
  type StoryboardProject,
  type CreateStoryboardProjectParams,
  type UpdateStoryboardProjectParams,
  type StoryboardProjectListQuery,
  type StoryboardProjectService,
  StoryboardProjectStatus,
  StoryboardProjectTemplate
} from '../../types/storyboardProject'
import { contentToStoredDocument, storedDocumentToContent } from './indexedDB/types'

/**
 * 生成唯一ID
 */
function generateId(): string {
  return `sb_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
}

/**
 * 分镜项目服务实现
 */
class StoryboardProjectServiceImpl implements StoryboardProjectService {
  /**
   * 获取项目列表
   */
  async getProjects(query?: StoryboardProjectListQuery): Promise<StoryboardProject[]> {
    try {
      console.log('[分镜项目服务] 获取项目列表', query)

      // 获取所有分镜类型的文档
      let documents = await db.documents
        .where('type')
        .equals(ContentType.STORYBOARD)
        .toArray()

      // 转换为Content对象
      let projects = documents.map(doc => {
        const content = storedDocumentToContent(doc)
        return this.contentToProject(content)
      })

      // 应用查询过滤
      if (query) {
        // 按状态筛选
        if (query.status) {
          projects = projects.filter(p => p.status === query.status)
        }

        // 按模板筛选
        if (query.template) {
          projects = projects.filter(p => p.template === query.template)
        }

        // 按标签筛选
        if (query.tags && query.tags.length > 0) {
          projects = projects.filter(p =>
            p.tags && p.tags.some(tag => query.tags!.includes(tag))
          )
        }

        // 搜索关键词
        if (query.search) {
          const searchLower = query.search.toLowerCase()
          projects = projects.filter(p =>
            p.name.toLowerCase().includes(searchLower) ||
            (p.description && p.description.toLowerCase().includes(searchLower))
          )
        }

        // 排序
        if (query.sortBy) {
          const sortBy = query.sortBy
          const sortOrder = query.sortOrder || 'desc'
          projects.sort((a, b) => {
            const aVal = a[sortBy]
            const bVal = b[sortBy]
            if (aVal < bVal) return sortOrder === 'asc' ? -1 : 1
            if (aVal > bVal) return sortOrder === 'asc' ? 1 : -1
            return 0
          })
        }

        // 分页
        if (query.offset !== undefined || query.limit !== undefined) {
          const offset = query.offset || 0
          const limit = query.limit || projects.length
          projects = projects.slice(offset, offset + limit)
        }
      }

      console.log('[分镜项目服务] 获取到项目列表', projects.length)
      return projects
    } catch (error) {
      console.error('[分镜项目服务] 获取项目列表失败', error)
      return []
    }
  }

  /**
   * 根据ID获取项目
   */
  async getProjectById(id: string): Promise<StoryboardProject | null> {
    try {
      console.log('[分镜项目服务] 获取项目', id)

      const doc = await db.documents.get(id)
      if (!doc || doc.type !== ContentType.STORYBOARD) {
        console.log('[分镜项目服务] 项目不存在')
        return null
      }

      const content = storedDocumentToContent(doc)
      const project = this.contentToProject(content)

      console.log('[分镜项目服务] 获取到项目', project.name)
      return project
    } catch (error) {
      console.error('[分镜项目服务] 获取项目失败', error)
      return null
    }
  }

  /**
   * 创建新项目
   */
  async createProject(params: CreateStoryboardProjectParams): Promise<StoryboardProject> {
    try {
      console.log('[分镜项目服务] 创建项目', params.name)

      const now = new Date().toISOString()
      const id = generateId()

      // 使用传入的storyboardData，或创建空的初始数据
      let storyboardData: StoryboardData

      if (params.storyboardData) {
        // 使用传入的分镜数据（从AI生成或导入）
        storyboardData = {
          ...params.storyboardData,
          // 确保必需字段存在
          scenes: params.storyboardData.scenes || [],
          totalDuration: params.storyboardData.totalDuration || 0,
          videoFormat: params.storyboardData.videoFormat || {
            aspectRatio: 'STANDARD' as any,
            resolution: 'FULL_HD' as any,
            frameRate: 25
          },
          projectAssets: params.storyboardData.projectAssets || {
            characters: [],
            props: [],
            locations: [],
            music: [],
            soundEffects: []
          }
        }
      } else {
        // 创建空的初始数据
        storyboardData = {
          scenes: [],
          totalDuration: 0,
          videoFormat: {
            aspectRatio: 'STANDARD' as any,
            resolution: 'FULL_HD' as any,
            frameRate: 25
          },
          projectAssets: {
            characters: [],
            props: [],
            locations: [],
            music: [],
            soundEffects: []
          }
        }
      }

      console.log('[分镜项目服务] 分镜数据', {
        sceneCount: storyboardData.scenes?.length || 0,
        totalDuration: storyboardData.totalDuration || 0,
        hasData: !!params.storyboardData
      })

      // 创建Content对象
      const content: Content = {
        id,
        type: ContentType.STORYBOARD,
        title: params.name,
        data: storyboardData,
        status: 'DRAFT' as any,
        createdAt: new Date(now),
        updatedAt: new Date(now)
      }

      // 转换并保存到数据库
      const doc = contentToStoredDocument(content)
      await db.documents.put(doc)

      // 创建项目对象
      const project: StoryboardProject = {
        id,
        name: params.name,
        description: params.description,
        template: params.template,
        status: StoryboardProjectStatus.DRAFT,
        createdAt: now,
        updatedAt: now,
        path: params.path,
        tags: params.tags || [],
        stats: {
          sceneCount: storyboardData.scenes?.length || 0,
          totalDuration: storyboardData.totalDuration || 0,
          lastEditedAt: now
        },
        settings: {
          autoSave: true,
          backupEnabled: false,
          collaborationEnabled: false
        }
      }

      console.log('[分镜项目服务] 项目已创建', {
        id,
        sceneCount: project.stats.sceneCount,
        totalDuration: project.stats.totalDuration
      })
      return project
    } catch (error) {
      console.error('[分镜项目服务] 创建项目失败', error)
      throw error
    }
  }

  /**
   * 更新项目
   */
  async updateProject(id: string, params: UpdateStoryboardProjectParams): Promise<StoryboardProject> {
    try {
      console.log('[分镜项目服务] 更新项目', id)

      const doc = await db.documents.get(id)
      if (!doc || doc.type !== ContentType.STORYBOARD) {
        throw new Error('项目不存在')
      }

      const content = storedDocumentToContent(doc)
      const now = new Date().toISOString()

      // 更新Content
      if (params.name) {
        content.title = params.name
        if (content.type === ContentType.STORYBOARD) {
          content.data.title = params.name
        }
      }

      if (params.status) {
        content.status = params.status.toLowerCase() as any
      }

      content.updatedAt = new Date(now)

      // 保存更新
      const updatedDoc = contentToStoredDocument(content)
      await db.documents.put(updatedDoc)

      // 返回更新后的项目
      const project = this.contentToProject(content)
      if (params.name) project.name = params.name
      if (params.description !== undefined) project.description = params.description
      if (params.status) project.status = params.status
      if (params.tags) project.tags = params.tags
      if (params.stats) project.stats = { ...project.stats, ...params.stats }
      if (params.settings) project.settings = { ...project.settings, ...params.settings }

      console.log('[分镜项目服务] 项目已更新')
      return project
    } catch (error) {
      console.error('[分镜项目服务] 更新项目失败', error)
      throw error
    }
  }

  /**
   * 删除项目
   */
  async deleteProject(id: string): Promise<void> {
    try {
      console.log('[分镜项目服务] 删除项目', id)
      await db.documents.delete(id)
      console.log('[分镜项目服务] 项目已删除')
    } catch (error) {
      console.error('[分镜项目服务] 删除项目失败', error)
      throw error
    }
  }

  /**
   * 复制项目
   */
  async duplicateProject(id: string, newName?: string): Promise<StoryboardProject> {
    try {
      console.log('[分镜项目服务] 复制项目', id)

      const original = await this.getProjectById(id)
      if (!original) {
        throw new Error('原项目不存在')
      }

      const content = await this.getProjectContent(id)
      if (!content) {
        throw new Error('无法获取项目内容')
      }

      // 创建新项目
      const params: CreateStoryboardProjectParams = {
        name: newName || `${original.name} (副本)`,
        description: original.description,
        template: original.template,
        path: original.path,
        tags: original.tags
      }

      const newProject = await this.createProject(params)

      // 复制内容
      await this.updateProjectContent(newProject.id, content)

      console.log('[分镜项目服务] 项目已复制', newProject.id)
      return newProject
    } catch (error) {
      console.error('[分镜项目服务] 复制项目失败', error)
      throw error
    }
  }

  /**
   * 获取项目内容
   */
  async getProjectContent(id: string): Promise<StoryboardData | null> {
    try {
      console.log('[分镜项目服务] 获取项目内容', id)

      const doc = await db.documents.get(id)
      if (!doc || doc.type !== ContentType.STORYBOARD) {
        return null
      }

      const content = storedDocumentToContent(doc)
      if (content.type !== ContentType.STORYBOARD) {
        return null
      }

      return content.data
    } catch (error) {
      console.error('[分镜项目服务] 获取项目内容失败', error)
      return null
    }
  }

  /**
   * 更新项目内容
   */
  async updateProjectContent(id: string, data: StoryboardData): Promise<void> {
    try {
      console.log('[分镜项目服务] 更新项目内容', id)

      const doc = await db.documents.get(id)
      if (!doc || doc.type !== ContentType.STORYBOARD) {
        throw new Error('项目不存在')
      }

      const content = storedDocumentToContent(doc)
      if (content.type !== ContentType.STORYBOARD) {
        throw new Error('内容类型不匹配')
      }

      // 更新数据
      content.data = data
      content.updatedAt = new Date()

      // 保存
      const updatedDoc = contentToStoredDocument(content)
      await db.documents.put(updatedDoc)

      console.log('[分镜项目服务] 项目内容已更新')
    } catch (error) {
      console.error('[分镜项目服务] 更新项目内容失败', error)
      throw error
    }
  }

  /**
   * 获取最近访问的项目
   */
  async getRecentProjects(limit: number = 10): Promise<StoryboardProject[]> {
    try {
      console.log('[分镜项目服务] 获取最近项目', limit)

      // 获取所有分镜项目，按更新时间排序
      const documents = await db.documents
        .where('type')
        .equals(ContentType.STORYBOARD)
        .reverse()
        .limit(limit)
        .toArray()

      const projects = documents.map(doc => {
        const content = storedDocumentToContent(doc)
        return this.contentToProject(content)
      })

      console.log('[分镜项目服务] 获取到最近项目', projects.length)
      return projects
    } catch (error) {
      console.error('[分镜项目服务] 获取最近项目失败', error)
      return []
    }
  }

  /**
   * 标记项目为最近访问
   */
  async markProjectAccessed(id: string): Promise<void> {
    try {
      console.log('[分镜项目服务] 标记项目访问', id)

      const doc = await db.documents.get(id)
      if (!doc || doc.type !== ContentType.STORYBOARD) {
        return
      }

      const content = storedDocumentToContent(doc)
      content.updatedAt = new Date()

      const updatedDoc = contentToStoredDocument(content)
      await db.documents.put(updatedDoc)

      console.log('[分镜项目服务] 项目访问已标记')
    } catch (error) {
      console.error('[分镜项目服务] 标记项目访问失败', error)
    }
  }

  /**
   * 将Content转换为StoryboardProject
   */
  private contentToProject(content: Content): StoryboardProject {
    if (content.type !== ContentType.STORYBOARD) {
      throw new Error('内容类型不是分镜')
    }

    const data = content.data

    return {
      id: content.id,
      name: content.title,
      description: undefined, // StoryboardData中没有description字段，从Content.title获取
      template: StoryboardProjectTemplate.BLANK,
      status: this.mapContentStatusToProjectStatus(content.status),
      createdAt: content.createdAt.toISOString(),
      updatedAt: content.updatedAt.toISOString(),
      tags: [],
      stats: {
        sceneCount: data.scenes?.length || 0,
        totalDuration: data.totalDuration || 0,
        lastEditedAt: content.updatedAt.toISOString()
      },
      settings: {
        autoSave: true,
        backupEnabled: false,
        collaborationEnabled: false
      }
    }
  }

  /**
   * 映射Content状态到Project状态
   */
  private mapContentStatusToProjectStatus(status: string): StoryboardProjectStatus {
    switch (status) {
      case 'draft':
        return StoryboardProjectStatus.DRAFT
      case 'published':
        return StoryboardProjectStatus.COMPLETED
      case 'archived':
        return StoryboardProjectStatus.ARCHIVED
      default:
        return StoryboardProjectStatus.IN_PROGRESS
    }
  }
}

/**
 * 导出单例实例
 */
export const storyboardProjectService = new StoryboardProjectServiceImpl()
